<template>
	<view class="u-skeleton" :style="{overflow:showscoll()?'hidden':'auto'}">
		<view class="bodystyle" :key="timerform">
			<u-form labelPosition="left" :model="defaultForm" :rules="rules" ref="uForm">
				<view v-for="(item,index) in fields" :key="index">
					<u-form-item borderBottom :labelWidth="item.tag==='fc-input-table'?0:200"
						:label="item.tag==='fc-input-table'?'':item.label" :prop="item.vModel"
						:rules="[{ required: (formAuth[item.vModel]==2&&item.required)?true:false, message: item.placeholder, trigger: item.tag==='el-select'?'change':'blur' }]">
						<!-- {{item.tag}} -->
						<view v-if="item.tag!=='fc-input-table'" style="text-align: right;">
							{{defaultForm[item.vModel]}}
						</view>
						<view v-if="item.tag=='el-select'">
							<view>
								<view>1111
									{{getSelectDatas(defaultForm[item.vModel],item.options)}}
								</view>
							</view>
						</view>
						<view v-if="item.tag=='fc-input-table'">
							<view>
								<tableForm ref="tableForms" :formAuth="formAuth" :vmodel="item.vModel"
									:tableForm="item.children" :defaultForms="defaultForm[item.vModel]"></tableForm>
							</view>
						</view>
					
					</u-form-item>
				</view>
				<u-form-item label="意见" prop="comment" :labelWidth="170"
					:rules="[{ required: true, message: '请输入意见', trigger: 'blur' }]">
					<u-input border="surround" v-model="defaultForm.comment" :placeholder="'请输入意见'"></u-input>
				</u-form-item>
				<u-form-item>
					<view style="width: 100%;margin-top:20rpx">
						<view style="width:40%;float: left;">
							<u-button size="small" type="primary" @click="submitForm('uForm')"
								:loading="loading">同意</u-button>
						</view>
						<view style="width:40%;float: left;margin-left: 20%;">
							<u-button size="small" @click="reject()" :loading="loading">拒绝</u-button>
						</view>
					</view>
				</u-form-item>
			</u-form>
		</view>
		<view v-if="showSelect">
			<!-- 选择器 -->
			<u-picker :key="stimer" @cancel="showSelect=false" @confirm="comfirnSelect" :show="showSelect"
				:columns="[selectOptions]" keyName="label"></u-picker>
		</view>
	</view>
</template>

<script>
	import PROVINCE from './province';
	import singleTime from './singleTime.vue'
	import global from '@/plugins/global'
	import tableForm from './tableForm.vue'
	export default {
		components: {
			singleTime,
			tableForm
		},
		name: 'editForm',
		props: {
			backNodes: {
				type: Array,
				default () {
					return [];
				}
			},
			procInstId: {
				type: String,
				default () {
					return '';
				}
			},
			formData: {
				type: Object,
				default () {
					return {};
				}
			},
			applierChooseList: {
				type: Array,
				default () {
					return [];
				}
			},
			formAuth: {
				type: Object,
				default () {
					return {};
				}
			},
			processSettings: Object,
			defaultData: {
				type: Object,
				default () {
					return {};
				}
			}
		},
		data() {
			return {
				tableData: [],
				close1: true,
				notifymessage: '',
				stimer: null,
				fileList: [],
				show: true,
				value1: null,
				mode: 'range',
				timerform: null,
				showRange: false,
				myHeaders: {
					Authorization: '',
					TenantId: 0
				},
				checkModel: {},
				isCheck: false,
				userTimer: '',
				PROVINCE: PROVINCE,
				loading: false,
				defaultStyle: {
					width: '100%'
				},
				defaultForm: {},
				tableForm: {},
				fileList: [],
				rules: {},
				fields: [],
				approveData: {},
				selectUserData: {},
				selectedProcessKey: '',
				isEmpty: false,
				mark: '',
				tableMark: null,
				tableIndex: null,
				formTag: '',
				showSingle: false,
				showSingletime: false,
				showSelect: false,
				showdurationtime: false,
				approveForm: {
					'agree': true,
					'comment': '',
					'param': {},
					'procInstId': 0
				},
				selectOptions: [],
				mark: '',
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				tabletimer: '',
				showTable: true
			}
		},
		created() {
			this.actionData()
		},
		methods: {
			getSelectDatas(e, option) {
				if (!!e) {
					let name = ''
					option.forEach(row => {
						if (row.value == e) {
							name = row.label
						}
					})
					console.log(e, option, name, 'getSelectDatas');
					return name;
				} else {
					return '暂未选择'
				}
			},
			showscoll() {
				
				if(this.$refs.tableForms){
					return this.showSingle || this.showSingletime || this.showSelect || this.showdurationtime||this.$refs.tableForms[0].showTableChildForm||this.$refs.tableForms[0].showtableform
				}else{
					return this.showSingle || this.showSingletime || this.showSelect || this.showdurationtime
				}
				setTimeout(()=>{
					console.log(this.$refs.tableForms,'txts');
				},200)
			},
			changeRadio(e) {
				this.defaultForm[e.target.dataset.vmodel] = e.detail.value
				console.log('这是选择了radio', this.defaultForm);
			},
			addTable(e) {
				this.$refs.tableForms[0].add(e)
			},
			scroll: function(e) {
				console.log(e)
				this.old.scrollTop = e.detail.scrollTop
			},
			add(item) {
				let that = this;
				let obj = {};
				item.children.forEach(e => {
					this.$set(obj, e.vModel, !e.defaultValue ? null : e.defaultValue);
				});
				this.defaultForm[item.vModel].push(obj);
				this.$nextTick(() => {
					console.log(that.$refs.tableForms);
					that.$refs.tableForms[0].testData(that.defaultForm[item.vModel])
				})
				// this.showTable = false;
				// setTimeout(() => {
				// 	this.showTable = true;
				// }, 1)
				console.log(item.children, this.defaultForm[item.vModel], '---');
			},
			gettanleform(e) {
				console.log(e);
			},
			actionData() {
				this.approveForm = {
					'agree': true,
					'comment': '',
					'param': {},
					'procInstId': 0
				};
				this.defaultForm = {};
				this.tableForm = {};
				this.defaultForm = {};
				this.rules = {};
				this.fields = [];
				console.log(this.formData);
				this.formData.fields.forEach(field => {
					if (field.dataSources === "dict") {
						uni.$u.http.request({
							url: global.BACKEND_URL + "/base/dict/query/" + field.api,
							method: 'POST',
							data: {},
							header: {
								Authorization: field.token,
								TenantId: 0
							}
						}).then(res => {
							if (res.data.code === "S00000") {
								field.options = [];
								res.data.data.forEach(e => {
									field.options.push({
										label: e.dictName,
										value: e.dictCode,
									});
								});
							}
						});
					} else if (field.dataSources === "api") {
						field.options;
						uni.$u.http.request({
							url: field.api,
							method: 'POST',
							data: {},
							header: {
								Authorization: field.token,
								TenantId: 0,
							},
							success: (res) => {
								field.options = res.data;
							}
						});
					}
					console.log(field.tag);
					if (field.tag !== 'grid') {
						if (this.formAuth[field.vModel] == 1) {
							field.disabled = true;
							this.fields.push(field);
						} else if (this.formAuth[field.vModel] == 2) {
							field.disabled = false;
							this.fields.push(field);
						} else if (this.formAuth[field.vModel] == undefined) {
							field.disabled = true;
							this.fields.push(field);
						} else {
							field.hide = true;
						}
						// this.fields.push(field);
						this.$set(this.defaultForm, field.vModel, field.defaultValue == undefined ? null : field
							.defaultValue);
					} else {
						field.children.forEach(e => {
							console.log(this.formAuth[e.vModel]);
							if (this.formAuth[e.vModel] == 1) {
								e.disabled = true;
								this.fields.push(e);
							} else if (this.formAuth[e.vModel] == 2) {
								e.disabled = false;
								this.fields.push(e);
							} else if (this.formAuth[e.vModel] == undefined) {
								e.disabled = true;
								this.fields.push(e);
							} else {
								e.hide = true;
							}
							// this.fields.push(e);
						});
					}
					if (field.tag == "fc-input-table") {
						let obj = {};
						field.children.forEach(e => {

							if (this.formAuth[e.vModel] == 1) {
								e.disabled = true;
							} else if (this.formAuth[e.vModel] == 2) {
								e.disabled = false;
							} else if (this.formAuth[e.vModel] == undefined) {
								e.disabled = true;
							} else {
								e.hide = true;
							}
							this.$set(obj, e.vModel, !e.defaultValue ? null : e.defaultValue);
							this.$set(this.tableForm, e.vModel, e.defaultValue == undefined ? null : e
								.defaultValue);
						});
						this.defaultForm[field.vModel] = [obj];
					}
					this.defaultForm = JSON.parse(JSON.stringify(this.defaultData));
				});
				console.log(this.defaultForm, 'dmoajdajhdoajdo');

				this.fields.forEach(row => {
					if (this.formAuth[row.vModel] == 2 && row.required) {
						this.rules[row.vModel] = [{
							required: true,
							message: row.placeholder,
							trigger: 'blur'
						}]
					}
				})
				this.rules.comment = [{
					required: true,
					message: '请输入审批意见',
					trigger: 'blur'
				}]
				setTimeout(() => {
					this.applierChooseList.forEach(e => {
						this.approveData[e.paramKey] = [];
						this.selectUserData[e.paramKey] = '';
					});
				}, 100);
			},
			downloadFile(files) {
				console.log(files, '点进来了');
				tt.downloadFile({
					"url": global.BACKEND_URL + "/extension/file/download?fileName=" + files.fileName,
					success(res) {
						console.log(JSON.stringify(res), '下载成功');
					},
					fail(res) {
						console.log(`downloadFile fail: ${JSON.stringify(res)}`);
					}
				});
				let headers = {
					"Authorization": uni.getStorageSync('token'),
					"TenantId": 0,
				}
				console.log(headers);
				const downloadTask = tt.downloadFile({
					url: global.BACKEND_URL + "/extension/file/download?fileName=" + files.fileName,
					header: headers,
					success: res => {
						console.log('下载成功', res, 'dkoakdoa');
						if (res.statusCode === 200) {
							this.isShowProgress = false;
							console.log('下载成功');
						}
						let that = this;
						const filePath = res.tempFilePath;
						console.log(filePath, '路径---');
						uni.openDocument({
							filePath: filePath,
							showMenu: true,
							success: function(res) {
								console.log('打开文档成功');
							}
						});

					}
				})

				downloadTask.onProgressUpdate((res) => {
					if (res.progress > 0) {
						this.isShowProgress = true;
					}
					this.progress = res.progress;
					console.log('下载进度：' + res.progress);
					console.log('已下载长度：' + res.totalBytesWritten);
					console.log('文件总长度：' + res.totalBytesExpectedToWrite);
				})
			},
			confrimSingleTime(e) {
				this.defaultForm[this.formTag] = e.time;
				this.showSingletime = false;
			},
			cancelSingleTime(e) {
				this.showSingletime = false;
			},
			confrimTimeDuration(e) {
				this.defaultForm[this.formTag] = e.time;
				this.showdurationtime = false;
			},
			cancelTimeDuration(e) {
				this.showdurationtime = false;
			},
			beforeRead(item) {
				this.mark = item
			},
			comfirnSelect(e) {
				this.showSelect = false;
				this.defaultForm[this.formTag] = e.value[0].value
				console.log(e, '进来了吗', this.defaultForm[this.formTag]);
				this.stimer = new Date().getTime()
			},
			openSelect(e, o) {
				this.selectOptions = o
				this.formTag = e;
				this.showSelect = true;
				this.stimer = new Date().getTime()
			},
			getData(e) {
				console.log(e);
			},
			comfirnSingletime(e) {
				console.log(e);
				console.log(e, '====');
				this.showSingletime = false;
				this.defaultForm[this.formTag] = e.value + ':00'
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
			opendurationTime(e) {
				this.formTag = e;
				this.showdurationtime = true;
			},
			openSingleTime(e) {
				this.formTag = e;
				this.showSingletime = true;
			},
			openRangeDate(e) {
				this.mode = 'range';
				this.formTag = e;
				this.showRange = true;
			},
			openSingleDate(e) {
				this.mode = 'single';
				this.formTag = e;
				this.showSingle = true;
			},
			confirmSingleDate(e) {
				console.log(e, '这是啥');
				this.showSingle = false;
				this.defaultForm[this.formTag] = e + ' 00:00:00'

			},
			confirmRangeDate(e) {
				console.log(e, '这是啥');
				this.showRange = false;
				this.defaultForm[this.formTag] = [e[0] + ' 00:00:00', e[e.length - 1] + ' 00:00:00']
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				console.log(event, '---');
				let token = uni.getStorageSync('token')
				let that = this
				uni.uploadFile({
					url: global.BACKEND_URL + '/extension/file/upload', //仅为示例，非真实的接口地址
					fileType: 'image',
					filePath: event.file[0].url,
					name: 'file',
					header: {
						'Authorization': 'Bearer ' + token,
						'Content-Type': 'multipart/form-data',
						'TenantId': 0,
					},
					success: (uploadFileRes) => {
						if (!this.defaultForm[this.mark.vModel]) {
							this.defaultForm[this.mark.vModel] = [];
						}
						this.defaultForm[this.mark.vModel].push({
							fileUrl: JSON.parse(uploadFileRes.data).data[0].fileUrl,
							fileName: JSON.parse(uploadFileRes.data).data[0].encodedFileName,
							originalFileName: JSON.parse(uploadFileRes.data).data[0].fileName
						});
						console.log('返回的数据', JSON.parse(uploadFileRes.data).data[0])
					}
				});
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://192.168.2.21:7001/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},

			getSelectData(e, istable, index, tableKey = null) {
				console.log(e, istable, index, tableKey, this.defaultForm, '--------');
				let param = {};
				if (e.param) {
					let that = this;
					e.param.forEach(p => {
						if (that.defaultForm[p.field]) {
							param[p.field] = that.defaultForm[p.field];
						}
						if (istable && !that.defaultForm[p.field]) {
							param[p.field] = that.defaultForm[tableKey][index][p.field];
						}
					});
				}
				console.log(param, '这是获取到得参数');
				if (e.dataSources === "dict") {
					uni.$u.http.request({
						url: global.BACKEND_URL + "/base/dict/query/" + e.api,
						method: 'POST',
						data: {},
						header: {
							Authorization: field.token,
							TenantId: 0
						}
					}).then(res => {
						if (res.data.code === "S00000") {
							let arr = [];
							res.data.data.forEach(e => {
								arr.push({
									label: e.dictName,
									value: e.dictCode,
								});
							});
							e.options = arr;
						}
					});
				} else if (e.dataSources === "api") {
					uni.$u.http.request({
						url: e.api,
						data: param,
						methods: 'POST',
						header: {
							Authorization: e.token
						},
						success: (res) => {
							e.options = res.data;
						}
					});
				}
			},
			checkData(required, val, p, vmodel) {
				if (this.isCheck && required && !val) {
					this.checkModel[vmodel] = true;
					return p;
				}
				this.checkModel[vmodel] = false;
				return "";
			},
			del(item, index, row) {
				if (this.defaultForm[item.vModel].length < 2) {
					this.$message.info("当前表格只有一行，无法删除");
					return;
				}
				this.defaultForm[item.vModel].splice(index, 1);
			},
			showFiles(e) {
				window.open(e);
			},
			markfile(e, type = null, index = null) {
				if (type && index !== null) {
					this.mark = type;
					this.tableMark = e;
					this.tableIndex = index;
				} else {
					this.mark = e;
				}
			},
			onProgress(e) {},
			beforeUpload(e) {
				const isOver = e.size / 1024 / 1024 < this.mark.fileSize;
				// 限制文件上传大小
				if (!isOver) {
					this.$message.error('上传图片大小不能超过 ' + this.mark.fileSize + 'MB!');
					return false;
				}
			},
			beforeUploadTable(e) {
				const isOver = e.size / 1024 / 1024 < this.tableMark.fileSize;
				// 限制文件上传大小
				if (!isOver) {
					this.$message.error('上传图片大小不能超过 ' + this.tableMark.fileSize + 'MB!');
					return false;
				}
			},
			openChoose(e) {
				this.$refs.userchoose.dialogVisible = true;
				this.selectedProcessKey = e;
				this.$refs.userchoose.timer = new Date().getTime();
				this.approveData[this.selectedProcessKey].length && this.$refs.userchoose.setCheckedKeys(this.approveData[
					this.selectedProcessKey]);
			},
			// 条件回调
			getConditionData(e) {
				if (!e) {
					return false;
				}
				let arr = [];
				let users = [];
				e.forEach(r => {
					if (r.primaryCode.indexOf('org') === -1) {
						arr.push(r.primaryId);
						users.push(r.label);
					}
				});
				this.approveData[this.selectedProcessKey] = arr;
				this.selectUserData[this.selectedProcessKey] = users.join(' / ');
				this.userTimer = new Date().getTime();
				console.log(e, 'www', this.approveData, this.selectUserData);
			},
			submitForm(formName) {
				let that = this;
				this.$nextTick(() => {
					console.log(this.$refs.tableForms[0].defaultForm);
					this.defaultForm[this.$refs.tableForms[0].vmodel] = this.$refs.tableForms[0].defaultForm
				})
				this.isCheck = true;
				setTimeout(() => {
					let checks = false;
					Object.keys(this.checkModel).forEach(e => {
						if (this.checkModel[e]) {
							checks = true;
						}
					});
					if (checks) {
						uni.$u.toast('您有必填项未填')
						return;
					}
					this.$refs.uForm.validate().then(res => {
						this.isEmpty = false;
						this.applierChooseList.forEach(e => {
							if (!this.approveData[e.paramKey].length) {
								this.isEmpty = true;
							}
						});
						if (this.isEmpty) {
							uni.$u.toast('请配置所有节点用户')
							return false;
						}
						this.loading = true;
						this.approveForm.procInstId = this.procInstId;
						this.approveForm.comment = this.defaultForm.comment;
						this.approveForm.param = this.defaultForm;
						delete this.approveForm.param.comment;
						this.$request(this.$api['workbench/approve'], this.approveForm, res => {
							this.$emit('approved', true);
							uni.$u.toast('审批完成')
							this.loading = false;
							uni.redirectTo({
								url: '/pages/approve/index'
							})
						}).catch(e => {
							this.loading = false;
						});
					}).catch(errors => {
						this.loading = false;
					})
				}, 100);
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
			handleRemoveFile(file) {
				let index = this.defaultForm[this.mark.vModel].findIndex(e => {
					return e.fileUrl == file.fileUrl;
				});
				this.defaultForm[this.mark.vModel].splice(index, 1);
			},
			getImgList(imgs) {
				let imgarr = [];
				imgs.forEach(e => {
					imgarr.push(e.fileUrl);
				});
				return imgarr;
			},
			handleRemoveTable(file) {
				console.log(file);
				let index = this.defaultForm[this.mark.vModel][this.tableIndex][this.tableMark.vModel].findIndex(e => {
					return e.fileUrl == file.response.data[0].fileUrl;
				});
				this.defaultForm[this.mark.vModel][this.tableIndex][this.tableMark.vModel].splice(index, 1);
				console.log(index, this.defaultForm[this.mark.vModel][this.tableIndex][this.tableMark.vModel]);
			},
			handleSuccessTable(e) {
				if (!this.defaultForm[this.mark.vModel][this.tableIndex][this.tableMark.vModel]) {
					this.defaultForm[this.mark.vModel][this.tableIndex][this.tableMark.vModel] = [];
				}
				this.defaultForm[this.mark.vModel][this.tableIndex][this.tableMark.vModel].push({
					fileUrl: e.data[0].fileUrl,
					fileName: e.data[0].fileName
				});
			},
			handlePreviewTable(file) {
				console.log(file);
			},
			handleRemove(file) {
				console.log(file);
				let index = this.defaultForm[this.mark.vModel].findIndex(e => {
					return e.fileUrl == file.response.data[0].fileUrl;
				});
				this.defaultForm[this.mark.vModel].splice(index, 1);
				console.log(index, this.defaultForm[this.mark.vModel]);
			},
			handleSuccess(e) {
				if (!this.defaultForm[this.mark.vModel]) {
					this.defaultForm[this.mark.vModel] = [];
				}
				this.defaultForm[this.mark.vModel].push({
					fileUrl: e.data[0].fileUrl,
					fileName: e.data[0].fileName
				});
			},
			handlePreview(file) {
				console.log(file);
			},
			handleExceed(files, fileList) {
				this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
			},
			beforeRemove(file, fileList) {
				return this.$confirm(`确定移除 ${ file.name }？`);
			}
		},

	}
</script>

<style lang="scss" scoped>
	.tableStyle {
		width: 100%;
		height: 700rpx;
		clear: both;
		padding: 20rpx;
		border: 1rpx solid #ccc;
		overflow: scroll;
		border-radius: 10rpx;
		margin-top: 10rpx;
	}

	.scroll-view_H {
		white-space: nowrap;
		width: 100%;
	}

	.scroll-view-item {
		height: 200rpx;
		line-height: 200rpx;
		text-align: center;
		font-size: 36rpx;
	}

	.scroll-view-item_H {
		display: inline-block;
		width: 100%;
		height: 200rpx;
		line-height: 200rpx;
		text-align: center;
		font-size: 36rpx;
		background-color: #11acf1;
	}

	.fileStyle {
		width: 520rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		padding: 10upx 20upx;
		color: #fff;
		border: 1rpx solid #ccc;
		position: relative;
		margin: 10rpx 0;
		color: #666;
		border-radius: 6rpx;
		position: relative;
	}

	.btnstyle {
		width: auto;
		padding: 0 16rpx;
		height: 50rpx;
		float: right;
		line-height: 50rpx;
		text-align: center;
		border: 1rpx solid #f2f2f2;
		font-size: 26rpx;
		margin-right: 10rpx;
		border-radius: 10rpx;
		background-color: #11acf1;
		color: #ffffff;
	}
</style>